<template>
  <!-- pages/map/map.wxml -->

  <view class="container-layout">
    <!-- 上部 -->
    <view class="map-wrapper">
      <map
        style="width: 100%; height: 100%"
        class="map"
        id="myMap"
        :scale="scale"
        :longitude="longitude"
        :latitude="latitude"
        :controls="controls"
        :markers="showCusMarkers ? cusMarkers : markers"
        @markertap="labeltap"
        @labeltap="labeltap"
        @regionchange="regionchange"
        @callouttap="callouttap"
        @tap="clickMap"
        show-location
      >
        <!-- 自定义气泡 微信小程序支持，支付宝小程序不支持，支付宝需要使用特定了xml文件进行高级定制渲染-->
        <!--  #ifdef MP-WEIXIN	  -->
        <cover-view slot="callout">
          <block v-for="item in cusMarkers" :key="item.id">
            <cover-view :marker-id="item.id" class="my-cus-callout">
              <cover-view
                class="my-cus-box"
                :class="item.id == calloutMarkId ? 'my-cus-box-active' : ''"
              >
                <cover-view class="left-xian">闲{{ item.content }}</cover-view>
                <cover-view class="right-info">
                  <cover-view class="right-price">¥{{ item.price }}</cover-view>
                  <cover-view class="right-num"
                    >快{{ item.kuai }} 慢{{ item.man }}</cover-view
                  >
                </cover-view>
              </cover-view>
            </cover-view>
          </block>
        </cover-view>
        <!--  #endif -->
      </map>
      <!-- 新增搜索组件，点击跳转到绑定充电桩 -->
      <view class="search-box" style="border-radius: 18rpx" @tap="editClick">
        <view class="search-inner">
          <image src="/static/images/icon_input.png" class="icon_input" />
          <span class="search-placeholder">请输入充电桩号</span>
        </view>
      </view>

      <!-- 新增点击气泡显示充电桩详情信息 -->
      <view class="station-detail" v-if="calloutMarkId !== ''">
        <view @tap="goDetail">
          <view class="station-title">
            <image
              src="/static/images/icon-map-zhuang.png"
              class="station-title-icon"
            />
            <text>{{ calloutMarkItem.station_name }}</text>
          </view>
          <view class="station-type">
            <uni-tag
              :inverted="true"
              :text="stationType(calloutMarkItem.station_type)"
              type="warning"
              size="small"
            />
          </view>
          <view class="price-type">
            <view class="station-price">
              <text class="price-small">¥</text>
              {{ calloutMarkItem.station_price }}
            </view>
            <view class="station-type">
              <view class="kuai-box">
                <view class="kuai">快</view>
                数量：{{ calloutMarkItem.nums_free_kuai }}
              </view>
              <view class="man-box">
                <view class="man">慢</view>
                数量：{{ calloutMarkItem.nums_free_man }}
              </view>
            </view>
          </view>
        </view>
        <view class="device-item-distance">
          <view class="left-area">
            <uni-icons type="location" size="18"></uni-icons>
            <!-- <van-icon name="location-o" size="14" /> -->
            {{ calloutMarkItem.station_area }}
            {{ calloutMarkItem.station_address }}
          </view>
          <view class="icon-area" @tap="clickOpenNav">
            <image
              class="icon-area-img"
              src="/static/images/icon_distance.png"
            ></image>
            {{ changeDistance(calloutMarkItem.distance) }}km
          </view>
        </view>
      </view>

      <!-- 功能区 -->
      <!-- 刷新 -->
      <cover-view class="cover-refresh">
        <cover-image
          class="choose-refresh"
          @tap="selfLocationClick"
          src="/static/images/icon_location.png"
        />
      </cover-view>
      <!-- 缩小 -->
      <view class="cover-smaller">
        <cover-image
          class="icon-set"
          @tap="setSmallerClick"
          src="/static/images/smaller.png"
        />
      </view>
      <!-- 放大 -->
      <view class="cover-bigger">
        <cover-image
          class="icon-set"
          @tap="setBiggerClick"
          src="/static/images/bigger.png"
        />
      </view>
    </view>

    <!-- 底部布局 -->
    <view class="bottom-layout" id="bottom-layout"></view>
    <TabBarCus pageName="index" />
  </view>
</template>
<script>
import TabBarCus from "../../components/TabBarCus.vue";
import { changeDistance, stationType, openNav } from "../../utils/util.js"
const app = getApp();
let Sign = app.globalData.Sign;
let Store = app.globalData.Store;
let Api = app.globalData.Api;
//定义全局变量
const defaultScale = 11;
var mapId = 'myMap';
var bottomHeight = 0;
var windowHeight = 0;
var windowWidth = 0;

//读取当下目录 获取站点列表
export default {
  components: { TabBarCus },
  data() {
    return {
      changeDistance: changeDistance,
      stationType: stationType,
      list: [],
      calloutMarkId: '',
      calloutMarkItem: {
        station_name: ''
      },
      scale: defaultScale,
      latitude: 40.006103,
      longitude: 116.4965075,
      circles: [],
      mapHeight: 0,
      controls: [],
      markers: [],
      cusMarkers: [],
      homeActionLeftDistance: '0rpx',
      showTopTip: true,
      warningText: '顶部提示',
      showCusMarkers: false,
    };
  },
  // 2 生命周期
  onLoad: function () { },
  onShow: function () {
    uni.hideTabBar()
    this.initLoad();
  },
  onShareAppMessage() {
    return {
      title: app.globalData.Appname,
      path: 'pages/index/index'
    };
  },
  methods: {
    initLoad: function () {
      //授权定位
      this.locationAuth();
      var that = this;
      that.changeMapHeight();
    },

    refreshMap: function () {
      this.initLoad({});
    },

    // 设置地图高度
    changeMapHeight: function () {
      var that = this;
      uni.getSystemInfo({
        success: function (res) {
          windowHeight = res.windowHeight;
          windowWidth = res.windowWidth;
          //创建节点选择器
          var query = uni.createSelectorQuery();
          query.select('#bottom-layout').boundingClientRect();
          query.exec(function (res) {
            bottomHeight = res[0].height;
            that.setMapHeight();
          });
        }
      });
    },

    setMapHeight: function (params) {
      var that = this;
      // that.setData({
      that.mapHeight = windowHeight - bottomHeight + 'px'
      // });
      var controlsWidth = 40;
      var controlsHeight = 48;
      //设置中间部分指针
      // that.setData({
      that.controls = [
        {
          id: 1,
          iconPath: '/static/images/center-location.png',
          position: {
            left: (windowWidth - controlsWidth) / 2,
            top: (windowHeight - bottomHeight) / 2 - (controlsHeight * 3) / 4,
            width: 30,
            height: 30
          },
          clickable: true
        }
      ]
      // });
    },

    //设置扫码图片左边距
    setHomeActionLeftDistance: function () {
      var that = this;
      uni.getSystemInfo({
        success: function (res) {
          windowHeight = res.windowHeight;
          windowWidth = res.windowWidth;
          //创建节点选择器
          var query = uni.createSelectorQuery();
          //选择id
          query.select('#home-action-wrapper').boundingClientRect();
          query.exec(function (res) {
            //res就是 所有标签为mjltest的元素的信息 的数组
            // that.setData({
            that.homeActionLeftDistance = (windowWidth - res[0].width) / 2 + 'px'
            // });
          });
        }
      });
    },

    //授权定位
    locationAuth: function () {
      var that = this;
      uni.getSetting({
        success: (res) => {
          if (res.authSetting.location != undefined && res.authSetting.location != true) {
            uni.showModal({
              title: '请求授权当前位置',
              content: '需要获取您的地理位置，请确认授权',
              success: function (res) {
                //console.log(res)
                if (res.cancel) {
                  uni.showToast({
                    title: '拒绝授权',
                    icon: 'none',
                    duration: 1000
                  });
                } else if (res.confirm) {
                  uni.openSetting({
                    success: function (dataAu) {
                      if (dataAu.authSetting.location == true) {
                        uni.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        });
                        that.showMap();
                      } else {
                        uni.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        });
                      }
                    }
                  });
                }
              }
            });
          } else if (res.authSetting.location == undefined) {
            //调用wx.getLocation的API
            that.showMap();
          } else {
            //调用wx.getLocation的API
            that.showMap();
          }
        }
      });
    },

    // 4 地图区
    showMap: function () {
      var that = this;
      uni.getLocation({
        type: 'gcj02',
        altitude: true,
        //高精度定位  定位成功，更新定位结果
        success: (res) => {
          var latitude = res.latitude;
          var longitude = res.longitude;
          Store.setItem('latitude', latitude);
          Store.setItem('longitude', longitude);
          // that.setData({
          that.latitude = latitude,
            that.longitude = longitude,
            that.markers = that.markers,
            that.circles = [
              {
                latitude: res.latitude,
                longitude: res.longitude,
                color: '#F04806',
                fillColor: '#F04806',
                radius: 200,
                strokeWidth: 1
              }
            ]
          // });
          that.getMarkers();
        },
        // 定位失败回调
        fail: function (res) {
          console.log(res);
          uni.showToast({
            title: '定位失败了',
            icon: 'none'
          });
        },
        complete: function () {
          //隐藏加载框
          //wx.hideLoading()
        }
      });
    },

    //1 获取markers
    getMarkers() {
      //获取站点信息
      let station_lon = Store.getItem('longitude');
      let station_lat = Store.getItem('latitude');
      //console.log("1:"+station_lon)
      //console.log("2:" + station_lat)

      const signObject = {
        station_lon,
        station_lat
      };
      const signvalue = Sign.signutil(signObject);
      app.globalData
        .get(Api.getStationList, {
          station_lon,
          station_lat,
          sign: signvalue
        })
        .then((res) => {
          //2 获取站点信息
          let list = res.station_list;
          let markers = [];
          let cusMarkers = [];
          //3 赋值markers
          for (let item of list) {
            let marker = this.createMarker(item);
            let cusMarker = this.createMarker(item, 'bigger');
            markers.push(marker);
            cusMarkers.push(cusMarker);
          }
          //console.log(markers)
          // this.setData({
          this.markers = markers,
            console.log('this.markers: ', this.markers);
          this.cusMarkers = cusMarkers,
            console.log('this.cusMarkers: ', this.cusMarkers);
          this.list = list
          // });
        })
        .catch((e) => {
          console.log(e);
        });
    },

    //创建标记点
    createMarker(point, type) {
      // console.log(point)
      let latitude = point.station_lat;
      let longitude = point.station_lon;
      let marker = {};
      if (type === 'bigger') {
        marker = {
          id: parseInt(point.bid),
          content: point.nums_free_kuai + point.nums_free_man,
          //文本
          price: point.station_price,
          kuai: point.nums_free_kuai,
          man: point.nums_free_man,
          iconPath: '/static/images/ic_local.png',
          ids: point.station_id + ',' + point.distance,
          title: point.station_name,
          latitude: latitude,
          longitude: longitude,
          cdzOrdpc: point.cdzOrdpc,
          width: 12,
          height: 12,
          //#ifdef MP-WEIXIN
          //自定义气泡
          customCallout: {
            anchorY: 4, // Y轴偏移量
            anchorX: 0, // X轴偏移量
            display: 'ALWAYS', // 'BYCLICK':点击显示; 'ALWAYS':常显
          },
          // #endif
          //#ifdef MP-ALIPAY
          iconLayout: {
            params: {
              content: '闲' + (point.nums_free_kuai + point.nums_free_man - 0),
              width: 35,
              height: 35,
              title: point.nums_free_kuai + point.nums_free_man + '',
              iconPath: '/static/images/circle-xian.png',
              iconPathLocal: '/static/images/ic_local_new1.png',
              widthLocal: 7,
              heightLocal: 4,
              //文本
              price: '¥' + point.station_price,
              kuai: '快' + point.nums_free_kuai,
              man: '慢' + point.nums_free_man,
              bgColor: '#FF00FF',
            },
            src: '/static/mapBigger.xml',
          },
          // #endif
        };
      } else {
        //#ifdef MP-WEIXIN
        marker = {
          id: parseInt(point.bid),
          iconPath: "../../static/images/ic_local.png",
          // iconPath: point.cdzOrdpc == 92 ? '/static/images/ic_address2.png' : '/static/images/ic_address.png',
          ids: point.station_id + "," + point.distance,
          title: point.station_name,
          latitude: latitude,
          longitude: longitude,
          cdzOrdpc: point.cdzOrdpc,
          width: 1,
          height: 1,
          //气泡label
          label: {
            content: point.nums_free_kuai + point.nums_free_man + '', //文本 
            color: '#fff', //文本颜色
            borderRadius: 30, //边框圆角
            borderWidth: 2, //边框宽度
            borderColor: '#ffffff', //边框颜色
            bgColor: '#FF992B', //背景色
            padding: 5, //文本边缘留白
            textAlign: 'center', //文本对齐方式  left, right, center,
            width: 30,
            height: 30,
            // fontSize:"18"//字体大小
          }
        };
        // #endif
        //#ifdef MP-ALIPAY
        marker = {
          id: parseInt(point.bid),
          iconPath: '/static/images/circle.png',
          title: point.station_name,
          latitude: latitude,
          longitude: longitude,
          width: 20,
          height: 20,
          iconLayout: {
            params: {
              width: '28',
              height: '28',
              title: point.nums_free_kuai + point.nums_free_man + '',
              iconPath: '/static/images/circle.png',
            },
            src: "/static/map.xml"
          },
        };
        // #endif
      }
      return marker;
    },
    //#ifdef MP-ALIPAY
    // 标示点移动触发
    regionchange(e) {
      // console.log('e: ', e);
      // return
      // console.log('scale', e.detail.scale)
      // this.setData({
      this.calloutMarkId = '',
        this.calloutMarkItem = {}
      // });
      let that = this;
      if (e.type == 'end') {
        if (e.scale && e.scale > 11) {
          console.log('放大');
          // that.setData({
          that.showCusMarkers = true
          // });
        } else if (e.scale && e.scale <= 11) {
          // that.setData({
          that.showCusMarkers = false
          // });
        }
      }
    },
    // #endif
    //#ifdef MP-WEIXIN
    // 标示点移动触发
    regionchange(e) {
      console.log('e: ', e);
      this.calloutMarkId = '',
      this.calloutMarkItem = {}
      let that = this;
      if (e.type == 'end') {
        if (e.detail.scale && e.detail.scale > 11) {
          console.log('放大');
          that.showCusMarkers = true
        } else if (e.detail.scale && e.detail.scale <= 11) {
          that.showCusMarkers = false
        }
      }
    },
    // #endif
    goDetail() {
      var cdzOrdpc = this.calloutMarkItem.cdzOrdpc;
      //  因为没有cdzOrdpc这个字段 所以我改了一下判断
      if (cdzOrdpc !== 92) {
        //充电桩
        uni.navigateTo({
          url: './../stationTidInfo/stationTidInfo?stationIdAndDistance=' + this.calloutMarkId
        });
      } else if (cdzOrdpc == 92) {
        //电瓶车
        uni.navigateTo({
          url: './../stationDpcInfo/stationDpcInfo?stationIdAndDistance=' + this.calloutMarkId
        });
      }
    },

    // marker点击
    markertap(e) {
      console.log('e-1: ', e);

      let markerId = e.markerId;
      let markers = this.markers;
      let cdzOrdpc = -1;
      for (var i = 0; i < markers.length; i++) {
        if (markerId == markers[i].id) {
          cdzOrdpc = markers[i].cdzOrdpc;
        }
      }
      if (cdzOrdpc == 91) {
        //充电桩
        uni.navigateTo({
          url: './../stationTidInfo/stationTidInfo?stationIdAndDistance=' + e.markerId
        });
      } else if (cdzOrdpc == 92) {
        //电瓶车
        console.log(2);
        uni.navigateTo({
          url: './../stationDpcInfo/stationDpcInfo?stationIdAndDistance=' + e.markerId
        });
      }
    },

    callouttap(e) {
      console.log('e: ', e);
      // callouttap
      let list = this.list;
      let clickItem = list.filter((item) => item.bid == e.detail.markerId);
      // this.setData({
      this.calloutMarkId = e.detail.markerId,
        this.calloutMarkItem = clickItem[0]
      // });
    },

    labeltap(e) {
      console.log('点击小的圆形气泡', e);
      let list = this.list;
      let clickItem = list.filter((item) => item.bid == e.detail.markerId);
      // this.setData({
      this.calloutMarkId = e.detail.markerId,
        this.calloutMarkItem = clickItem[0]
      // });
    },

    clickMap() {
      console.log('点击map');
      // this.setData({
      this.calloutMarkId = '',
        this.calloutMarkItem = {}
      // });
    },

    // 打开地图
    clickOpenNav() {
      var { station_lat, station_lon, station_name, station_address } = this.calloutMarkItem;
      openNav(station_lat, station_lon, station_name, station_address);
    },

    // 输入桩号入口
    editClick: function () {
      uni.navigateTo({
        url: '../sysInput/sysInput'
      });
    },

    // 点击缩小按钮
    setSmallerClick: function () {
      var that = this;
      // that.setData({
      that.scale = --that.scale
      if (that.scale <= 11) {
        that.showCusMarkers = false
      }
      console.log('that.scale: ', that.scale);
      console.log(' that.showCusMarkers: ', that.showCusMarkers);
      // });
      //console.log(that.data.scale)
    },

    // 点击放大按钮
    setBiggerClick: function () {
      var that = this;
      // that.setData({
      that.scale = ++that.scale
      if (that.scale > 11) {
        that.showCusMarkers = true
      }
      console.log('that.scale: ', that.scale);
      console.log(' that.showCusMarkers: ', that.showCusMarkers);
      // });
      //console.log(that.data.scale)
    },

    // 点击定位按钮
    selfLocationClick: function () {
      var that = this;
      //还原默认缩放级别
      // that.setData({
      that.scale = defaultScale
      // });
      //必须请求定位，改变中心点坐标
      that.requestLocation();
    },

    requestLocation: function () {
      var that = this;
      uni.getLocation({
        type: 'gcj02',
        success: function (res) {
          // that.setData({
          that.latitude = res.latitude,
            that.longitude = res.longitude
          // });
          let mpCtx = uni.createMapContext(mapId);
          mpCtx.moveToLocation();
          // this.moveTolocation();
        }
      });
    },

    // 移动到中心点
    moveToLocation: function () {
      let mpCtx = uni.createMapContext(mapId);
      mpCtx.moveToLocation();
    },

    // 点击放大点，显示详情
    showMore() { }
  }
};
</script>
<style >
@import "./index.css";
</style>
